<template>
    <div class="page">
        <div class="card-box">
            <div class="card">
                <el-form inline :model="searchInfo">
                  <el-form-item label="ID:">
                    <el-input v-model.number="searchInfo.id" placeholder="请输入id" type="number"></el-input>
                  </el-form-item>
                  <el-form-item label="名称:">
                    <el-input v-model="searchInfo.title" placeholder="请输入名称"></el-input>
                  </el-form-item>
                  <el-form-item label="状态:">
                    <el-select v-model="searchInfo.status" clearable placeholder="请选择状态" @change="statusSelectChange">
                      <el-option v-for="item in statusOptions" 
                      :key="item.value" 
                      :label="item.label"
                      :value="item.value"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" icon="search" @click="onSearch">查询</el-button>
                    <el-button icon="refresh" @click="onReset">重置</el-button>
                  </el-form-item>
                </el-form>
            </div>
        </div>
        <div class="card-box">
            <div class="card">
                <el-button type="primary" icon="plus" @click="onAdd">新增</el-button>
                <el-button icon="delete" @click="onDelete">删除</el-button>
                <el-table :data="tableData" style="margin-top: 10px;" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55"></el-table-column>
                    <el-table-column label="id" prop="id"></el-table-column>
                    <el-table-column label="名称" prop="title"></el-table-column>
                    <el-table-column label="权重" prop="weight"></el-table-column>
                    <el-table-column label="状态">
                        <template #default="scope">
                            {{ formatStatus(scope.row.status) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="按钮组">
                      <template #default="scope">
                        <el-button type="primary" link icon="edit" @click="onEdit(scope.row)">修改</el-button>
                      </template>
                      
                    </el-table-column>
                </el-table>
                <div style="display: flex;justify-content: flex-end;padding: 20px;">
                    <el-pagination 
                    :total="total" 
                    :current-page="page"  
                    :page-size="pageSize" 
                    :page-sizes="[10, 30, 50, 100]"
                    @current-change="handleCurrentChange"
                    @size-change="handleSizeChange"
                    layout="total, sizes, prev, pager, next, jumper"></el-pagination>
                </div>
            </div>
        </div>

        <el-dialog v-if="editDialogVisible" v-model="editDialogVisible" :title="isAdd ? '新增' : '编辑'">
            <el-form :model="editInfo" style="max-height: 50vh;overflow: scroll;">
              <el-form-item label="名称">
                <el-input v-model="editInfo.title" placeholder="请输入名称" clearable></el-input>
              </el-form-item>
              <el-form-item label="图片">
                <draggable 
                  v-model="editInfoPictures" 
                  draggable=".edit-info-picture-item"
                  item-key="index"
                  style="display: flex;flex-wrap: wrap;width: 100%;"
                  >
                  <template #item="{element}">
                    <div v-if="element.type == 'button'" class="edit-info-picture-item-box" style="border-radius: 20px;border: 1px dashed #ccc;">
                      <el-upload
                        :show-file-list="false"
                        :auto-upload="false"
                        :multiple="true"
                        accept="image/*"
                        :on-change="onPictureSelect"
                        >
                        <div style="width: 200px;height: 200px; display: flex;justify-content: center; align-items: center;">
                          <el-icon size="28px">
                            <Plus />
                          </el-icon>
                        </div>
                      </el-upload>
                    </div>
                    <div v-else class="edit-info-picture-item edit-info-picture-item-box" style="position: relative;">
                      <img v-if="element.url" style="width: 100%; height: 100%;" :src="IMAGE_BASE_URL + element.url">
                      <img v-else-if="element.fileUrl" style="width: 100%; height: 100%;" :src="element.fileUrl">
                      <div v-else>错误</div>
                      <el-icon size="20px" style="position:absolute;top: 10px; right: 10px;background-color: white;border-radius: 10px;padding: 5px;border: 1px solid #000;" 
                      @click="onPictureDelete(element)">
                        <Delete />
                      </el-icon>
                    </div>
                  </template>
                </draggable>
              </el-form-item>
              <el-form-item label="权重">
                <el-input v-model.number="editInfo.weight" placeholder="请输入权重" type="number"></el-input>
              </el-form-item>
              <el-form-item label="统跳">
                <el-input v-model="editInfo.jump_url" placeholder="请输入统跳地址"></el-input>
              </el-form-item>
              <el-form-item label="状态:">
                <el-select v-model="editInfo.status" clearable placeholder="请选择状态" @change="statusSelectChange">
                    <el-option v-for="item in statusOptions" 
                    :key="item.value" 
                    :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <template #footer>
                <div>
                    <el-button @click="editDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="onSave">确 定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script>
export default {
  name: 'BannerManager',
}
</script>

<script setup>
import { watch, ref, nextTick, onBeforeUnmount, onMounted} from 'vue';
import { 
    deleteBannerList, 
    getBannerList,
    createBanner,
    updateBanner,
} from '@/api/public'
import {
  uploadPicture
} from '@/api/upload'

import { ElMessage } from "element-plus"
import draggable from 'vuedraggable'
import { getFileMd5 } from "@/utils/md5"
import {IMAGE_BASE_URL, statusOptions, formatStatus} from "@/common/const";

import '@wangeditor/editor/dist/css/style.css'

//修复Element Plus错误警告 | Popper: Detected CSS transitions on at least one of the following
import { createPopper } from '@popperjs/core';
const popper = document.querySelector('.popper');
const reference = document.querySelector('.reference');
createPopper(reference, popper, {
  modifiers: [{
    name: 'computeStyles',
    options: {
      adaptive: false,
    },
  }],
});

const searchInfo = ref({})

const page = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])

const editDialogVisible = ref(false)
const isAdd = ref(false)
const editInfo = ref({})
const editInfoDate = ref([])
const editInfoPictures = ref([])
const selectRows = ref([])


const statusSelectChange= (val) => {
    if (val) {
        searchInfo.value.status = val
    } else {
        searchInfo.value.status = null
    }
}

const onSearch = () => {
    page.value = 1
    pageSize.value = 10
    getTableData()
}
const onReset = () => {
    searchInfo.value = {}
}


const onAdd = () => {
  isAdd.value = true
  editDialogVisible.value = true
  editInfo.value = { status: 2}
  editInfoPictures.value = [
    {
      index: -1,
      type: "button"
    }
  ]

}

const onEdit = async(row) => {
  isAdd.value = false
  editDialogVisible.value = true

  await nextTick()

  editInfo.value = { ...row }
  let items = []
  if (row.pictures) {
    let pictures = JSON.parse(row.pictures)
    for (let index = 0; index < pictures.length; index++) {
      const element = pictures[index];
      items.push({
        index: index,
        file: null,
        fileUrl: '',
        url: element.url,
        width: element.width,
        height: element.height,
        type: "picture",
      })
    }
  }
  
  items.push({
    index: -1,
    type: "button",
  })
  editInfoPictures.value = items


}

const onPictureSelect = (uploadFile, uploadFiles) => {
  let position = editInfoPictures.value.length - 1
  editInfoPictures.value.splice(position, 0,
    {
      index: position,
      file: uploadFile.raw,
      fileUrl: URL.createObjectURL(uploadFile.raw),
      url:'',
      width:0,
      height:0,
      type: "picture",
    }
  )
}

const onPictureDelete = (element) => {
  editInfoPictures.value.splice(editInfoPictures.value.indexOf(element), 1)
}


const onDelete = async() => {
  const ids = selectRows.value.map(item => item.id)
  const res = await deleteBannerList({ ids })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: res.msg
    })
    if (tableData.value.length === ids.length && page.value > 1) {
      page.value--
    }
    getTableData()
  } else {
    ElMessage({
      type: 'error',
      message: `${res.msg}`,
      showClose: true
    })
  }
}

const onSave = async() => {

  var uploadReqList = []
  var uploadResultMap = new Map()
  for (let index = 0; index < editInfoPictures.value.length; index++) {
    const element = editInfoPictures.value[index];
    if(element.type === 'picture' && element.file) {
      let md5 = await getFileMd5(element.file)
      uploadResultMap.set(md5, element)
      let fd = new FormData()
      fd.append('file', element.file)
      uploadReqList.push(uploadPicture(fd))
    }
  }

  if(uploadReqList.length > 0){
    let uploadResult = await Promise.all(uploadReqList)
    .catch(error => console.error(error));
    for (let index = 0; index < uploadResult.length; index++) {
      const element = uploadResult[index];
      const item = uploadResultMap.get(element.data.md5)
      item.url = element.data.url
      item.width = element.data.width
      item.height = element.data.height
    }
  }

  var pictures = []
  for (let index = 0; index < editInfoPictures.value.length; index++) {
    const element = editInfoPictures.value[index];
    if(element.type === 'picture') {
      pictures.push({
        url: element.url,
        width: element.width,
        height: element.height
      })
    }
  }
  editInfo.value.req_images = pictures

  var res
  if(isAdd.value){
    res = await createBanner(editInfo.value)
  } else {
    res = await updateBanner(editInfo.value)
  }

  if(res.code === 0){
    editDialogVisible.value = false
    ElMessage({
      type: 'success',
      message: "操作成功",
      showClose: true
    })
    getTableData()
  } else {
    ElMessage({
      type: 'error',
      message: `${res.msg}`,
      showClose: true
    })
  }

}



// 批量操作
const handleSelectionChange = (val) => {
  selectRows.value = val
}
// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const getTableData = async() => {
    try {
        if (!searchInfo.value.id && (searchInfo.value.id !== 0)){
          delete searchInfo.value.id
        }
        if (!searchInfo.value.title){
          delete searchInfo.value.title
        }
        const res = await getBannerList({page: page.value, page_size: pageSize.value, ...searchInfo.value})
        if(res.code === 0){
            tableData.value = res.data.list
            total.value = res.data.total
        } else {
            ElMessage({
                type: 'error',
                message: `${res.msg}`,
                showClose: true
            })
        }
    } catch (error) {
        ElMessage({
            type: 'error',
            message: `${error}`,
            showClose: true
        })
    }
}


//初始化
getTableData()


</script>

<style lang="scss" scoped>
.edit-info-picture-item-box{
  width: 200px;
  height: 200px;
  margin-right: 10px;
  margin-bottom: 10px;
  cursor: pointer;
}

</style>

<style lang="scss">
</style>